/*
 * @Description:
 * @Author: william
 * @Date: 2024-05-06 10:49:50
 * @LastEditors: william
 * @LastEditTime: 2025-04-11 16:26:31
 */
import echarts from '@/utils/_echarts'
import 'echarts/lib/component/polar' //  (reading 'findAxisModel')"
import { debounce } from '@/utils'

export const useChartMixin = _this => {
  const { myChart, autoResize = true } = _this
  const { theme, language } = storeToRefs(useAppStore())
  const axisLineColor = computed(() => {
    return theme.value === 'theme-white' ? '#666666' : '#d5e4f6'
  })
  const splitLineColor = computed(() => {
    return theme.value === 'theme-white' ? '#dddddd' : '#325597'
  })
  watch(theme, nv => {
    _this.setOptions(theme)
  })
  let __resizeHanlder = null

  const initChart = _ => {
    if (!myChart.value) {
      myChart.value = markRaw(echarts.init(_this.refChart.value, 'macarons'))
    }
    _this.setOptions && _this.setOptions(theme)
    if (autoResize) {
      __resizeHanlder = debounce(() => {
        if (myChart.value) {
          _this.setOptions && _this.setOptions(theme)
          myChart.value.resize()
        }
      }, 100)
      window.addEventListener('resize', __resizeHanlder)
    }
    // 监听侧边栏的变化
    const sidebarElm = document.getElementsByClassName('sidebar-container')[0]
    sidebarElm && sidebarElm.addEventListener('transitionend', __resizeHanlder)
  }

  onBeforeUnmount(_ => {
    if (!myChart.value) return
    if (autoResize) window.removeEventListener('resize', __resizeHanlder)
    const sidebarElm = document.getElementsByClassName('sidebar-container')[0]
    sidebarElm &&
      sidebarElm.removeEventListener('transitionend', __resizeHanlder)
    myChart.value.dispose()
    myChart.value = null
  })

  return {
    theme,
    language,
    axisLineColor,
    splitLineColor,
    initChart
  }
}
